import Base from 'models/base';

export default class AddressForm extends Base {
  static fields = ['province', 'city', 'area', 'street'];

  constructor(address) {
    super();

    if (address === undefined) {
      address = {
        sex: 1
      };
      this.addressCode = {};
    } else {
      this.id = address.weChatUserInfoAddressId;
      this.isDefault = address.defaultAddress === 1;

      let addressCode = {};
      let codeFields = AddressForm.fields;
      for (let i = 0; i < codeFields.length; i++) {
        const codeField = codeFields[i];
        let code = address[`${codeField}Code`];
        let name = address[`${codeField}Name`];
        addressCode[codeField] = {
          code,
          name
        };
      }
      this.addressCode = addressCode;
    }

    let fields = ['buyerAddress', 'buyerName', 'sex', 'buyerPhone'];
    this.initObject(address, fields);
  }

  getFullAddress(){
    let addressCode = this.addressCode;
    let fields = AddressForm.fields;
    let fullAddress = [];
    for (let i = 0; i < fields.length; i++) {
      const field = fields[i];
      let obj = addressCode[field];
      if (obj === undefined) {
        break;
      }
      fullAddress.push(obj.name);
    }
    return `${fullAddress.join('')} ${this.buyerAddress}`;
  }

  checkValid() {
    let fields = ['addressCode', 'buyerAddress', 'buyerName', 'buyerPhone'];
    let code = this.checkRequired(fields);
    if (code !== '') {
      return code;
    }

    let reg = /^1[3456789]\d{9}$/;
    if (!reg.test(this.buyerPhone)) {
      return 'buyerPhoneInvalid';
    }

    return '';
  }

  getObject(type) {
    let postData = {};
    let fields = ['buyerAddress', 'buyerName', 'sex', 'buyerPhone'];
    this.setPostData(postData, fields);

    if (type==='update') {
      postData.weChatUserInfoAddressId = this.id;
    }

    let codeFields = AddressForm.fields;
    let addressCode = this.addressCode;
    for (let i = 0; i < codeFields.length; i++) {
      const field = codeFields[i];
      let obj = addressCode[field];

      postData[`${field}Code`] = obj.code;
      postData[`${field}Name`] = obj.name;
    }

    return postData;
  }
}
